package com.liferay.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.liferay.dao.ClassDao;
import com.liferay.dao.ConnectDao;
import com.liferay.model.Classes;

public class ClassDaoImpl implements ClassDao {
	private Connection conn;
	private PreparedStatement pre;

	@Override
	public List<Classes> getListClassByFaculty(long fkFaculty) {
		String sql = "SELECT idClass, nameOfClass, fkFaculty FROM nlu_class WHERE fkFaculty=?";
		conn = ConnectDao.getConnection();
		List<Classes> list = new ArrayList<Classes>();
		try {
			pre = conn.prepareStatement(sql);
			pre.setLong(1, fkFaculty);
			ResultSet res = pre.executeQuery();
			while (res.next()) {
				Classes cla = new Classes();
				cla.setIdClass(res.getInt("idClass"));
				cla.setNameClass(res.getString("nameOfClass"));
				cla.setFkFaculty(res.getLong("fkFaculty"));
				list.add(cla);
			}
			res.close();
			pre.close();
			ConnectDao.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return list;
		}
		return list;
	}

	@Override
	public boolean deleteClass(Classes cla) {
		String sql = "DELETE FROM nlu_class WHERE idClass=?;";
		conn = ConnectDao.getConnection();
		try {
			pre = conn.prepareStatement(sql);
			pre.setLong(1, cla.getIdClass());
			pre.executeUpdate();
			pre.close();
			ConnectDao.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean updateClass(Classes cla) {
		String sql = "UPDATE nlu_class SET nameOfClass=?,fkFaculty=? WHERE idClass=?;";
		conn = ConnectDao.getConnection();
		try {
			pre = conn.prepareStatement(sql);
			pre.setString(1, cla.getNameClass());
			pre.setLong(2, cla.getFkFaculty());
			pre.setLong(3, cla.getIdClass());
			pre.executeUpdate();
			pre.close();
			ConnectDao.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean addClass(Classes cla) {
		String sql = "INSERT INTO nlu_class(nameOfClass,fkFaculty) VALUES(?,?);";
		conn = ConnectDao.getConnection();
		try {
			pre = conn.prepareStatement(sql);
			pre.setString(1, cla.getNameClass());
			pre.setLong(2, cla.getFkFaculty());
			pre.executeUpdate();
			pre.close();
			ConnectDao.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
